#include <windows.h>
#include <stdio.h>
#include "window.h"
#include "utils.h"

struct window g_window;
HANDLE g_thread;
HANDLE g_stop_event;
HANDLE g_cmd_event;

enum command
{
    start,
    end
};

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

DWORD WINAPI thread(LPVOID lpParameter)
{
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR args, int cmd_show)
{
    MSG msg ;
    WNDCLASSEXW wnd = {0};

    wnd.hInstance = hInstance;
    wnd.lpszClassName = L"nland";
    wnd.lpfnWndProc = WndProc;
    wnd.style = CS_HREDRAW | CS_VREDRAW ;
    wnd.cbSize = sizeof(WNDCLASSEXW);

    wnd.hIcon = LoadIcon(NULL, IDI_WINLOGO);
    wnd.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
    wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
    wnd.hbrBackground = (HBRUSH)COLOR_APPWORKSPACE ;

    window_init(&g_window);
    if (window_create(&g_window, &wnd, cmd_show) == -1)
    {
        error_exit("window_create");
    }

    g_stop_event = CreateEvent(NULL, FALSE, FALSE, NULL);
    g_cmd_event = CreateEvent(NULL, FALSE, FALSE, NULL);
    g_thread = CreateThread(NULL, 0, thread, NULL, 0, NULL);
    if (g_thread == NULL)
    {
        error_exit("Cannot start checking thread");
    }

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    window_minimize(&g_window);
    CloseHandle(g_stop_event);
    CloseHandle(g_cmd_event);

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    CREATESTRUCT* cs;
    PAINTSTRUCT ps;
    HDC hdc;
    RECT rect;

    struct window* w = (struct window*)GetWindowLongPtr(hwnd, GWLP_USERDATA);

    switch (message)
    {
    case WM_COMMAND:
        break;

    case WM_CREATE:
        cs = (CREATESTRUCT*)lParam;
        w = (struct window*)cs->lpCreateParams;
        window_on_create(w);
        return 0;
        break;

    case WM_PAINT:
        hdc = BeginPaint(w->hwnd, &ps);
        GetClientRect(w->hwnd, &rect) ;
        window_paint(w, &rect, hdc);
        EndPaint(hwnd, &ps) ;
        return 0;
        break;

    case WM_SIZE:
        window_size(w, (int)wParam, LOWORD(lParam), HIWORD(lParam));
        return 0;
        break;

    case WM_DESTROY:
        SetEvent(g_stop_event);
        WaitForSingleObject(g_thread, INFINITE);
        PostQuitMessage(0);
        break;

    }

    return DefWindowProc(hwnd, message, wParam, lParam) ;
}

